import { createStore } from "vuex";

export default createStore({
  state: {
    count: 0,
    // 确保获取的值是 string 类型，如果为 null 则设置为 null
    userInfo: localStorage.getItem("user")
      ? JSON.parse(localStorage.getItem("user") as string)
      : null,
    // 从localStorage加载token，如果没有，则设置为空字符串
    token: localStorage.getItem("token") || "",
    todos: [],
    // 是否完成当日加经验
    experience: {
      comment: false,
      visit: false,
    },
    commentExperience: 0,
    visitExperience: 0,
    travelogueExperience: 0,
  },
  getters: {
    // 判断用户是否已登录（有 token）
    isLoggedIn: (state) => !!state.userInfo,
    getUserInfo: (state) => state.userInfo,
    getToken: (state) => state.token,
  },
  mutations: {
    // 初始化经验值
    setExperience(state) {
      (state.commentExperience = 5),
        (state.visitExperience = 5),
        (state.travelogueExperience = 5);
    },
    // 设置用户存储
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    // 重置经验系统
    resetExperience(state) {
      state.experience.comment = false;
      state.experience.visit = false;
    },
    // 访问页面加经验
    setVisitExperience(state) {
      state.experience.visit = true;
    },
    // 发评论加经验
    setCommentExperience(state) {
      state.experience.comment = true;
    },
    SET_COUNT(state, payload) {
      state.count = payload;
    },
    SET_USER(state, user) {
      state.userInfo = user;
      console.log(`output->user`, user);
      localStorage.setItem("user", JSON.stringify(user)); // 持久化到localStorage
    },
    REMOVE_USER(state) {
      state.userInfo = null;
      localStorage.removeItem("user"); // 删除localStorage中的用户信息
    },
    // 存储 token
    SET_TOKEN(state, token) {
      state.token = token;
      localStorage.setItem("token", token); // 持久化到localStorage
    },
    // 清除 token
    REMOVE_TOKEN(state) {
      state.token = "";
      localStorage.removeItem("token"); // 删除localStorage中的token
    },
  },
  actions: {
    // 异步设置 token
    async saveToken({ commit }, token) {
      commit("SET_TOKEN", token);
    },
    // 退出登录
    async logout({ commit }) {
      commit("REMOVE_TOKEN");
      commit("REMOVE_USER"); // 清空用户信息
    },
  },
  modules: {},
});
